package core;

public class PipeLine {

    private MyChannel channel;

    private EventLoop eventLoop;

    public HandlerContext headContext;

    public HandlerContext tailContext;

    public PipeLine(MyChannel channel, EventLoop eventLoop) {
        this.channel = channel;
        this.eventLoop = eventLoop;
        PipeHandler headHandler = new PipeHandler();
        this.headContext = new HandlerContext(headHandler, channel);
        PipeHandler tailHandler = new PipeHandler();
        this.tailContext = new HandlerContext(tailHandler, channel);
        // 构建链表
        this.headContext.next = this.tailContext;
        this.tailContext.prev = this.headContext;
    }

    public PipeLine addLast(Handler handler) {
        HandlerContext curr = new HandlerContext(handler, channel);

        // 连接在倒数第二个后面
        HandlerContext lastButOne = this.tailContext.prev;
        lastButOne.next = curr;
        curr.prev = lastButOne;

        // 连接在最后一个前面
        curr.next = tailContext;
        tailContext.prev = curr;

        return this;
    }
}
